function [ out,w ] = linear_classifier(data,out_w,type = 0)
  % function: 线性分类器
  %
  % type=1(default):训练模式
  %   data:数据
  %   out_w:结果
  %
  % type=1(default):计算模式
  %   data:数据
  %   out_w:参数矩阵w
  %
  % out:结果
  % w:参数矩阵w
  %
  % Extended description

	rates = [];
  switch (type)
  case 0
    % train
    limit = 1000;
    rate = rand(1,1);
		rate_r = 0.001;

    [amount,dim] = size(data);

    w = rand(dim+1,1);
    out = out_w;

		for i=1:limit
      [o,w,rate] = train( w,data,out,rate,rate_r);
			%printf('----%d\n',rate);
		end
    out = run(w,data,amount);
  case 1
    % run
    w = out_w;
    out = run(w,data,amount);
  end

end  % function

function [ o_s,w,rate ] = train( w,data,out,rate,rate_r )

  [amount,dim] = size(data);
  [ o_s,o_sd ] = run(w,data,amount,out);

  %计算w的导数 dw[i] = D(log(O))*x[i]
  dw = o_sd .* [data,ones(amount,1)];
	%计算w按照当前rate梯度下降后的w（w_tmp）
	w_temp = w + (sum(dw*rate)')./amount;
	%计算w_tmp的导数
	[ o_s_temp,o_sd_temp ] = run(w_temp,data,amount,out);
	%计算rate的梯度
	d_rate = sum(sum(o_sd_temp.* dw .* [data,ones(amount,1)]))./(amount*dim);
	%计算调整后rate
	rate += rate_r*d_rate;
	%计算调整后rate的梯度下降后的w（w_tmp）
  w += (sum(dw*rate)')./amount;
	

end  % train

function [ o_s,o_sd ] = run( w,data,amount,out=[])
  % run: Short description
  %
  % Extended description
  [amount,dim] = size(data);
  o = [data,ones(amount,1)] * w;
	o_s = sigmoid(o);
  if ~isempty(out)
    o_sd = out + sigmoid(o,3);
  end

end  % run
